const parser = new DOMParser()
const renderSVG = function (h, xml, opt) {
  const {nodeName, attributes, childElementCount, childNodes} = xml
  if (nodeName === '#document') {
    return renderSVG(h, xml.firstElementChild, opt)
  }
  const attrs = [...attributes].reduce(function (list, node) {
    const {nodeName: nName, nodeValue: nValue} = node
    list[nName] = nValue
    return list
  }, {})
  if (opt && opt.name) {
    attrs.name = opt.name
  }
  const children = childElementCount > 0 ? [...childNodes].map(node => renderSVG(h, node, opt)) : null
  return h(nodeName, {attrs}, children)
}
export default {
  name: 'r-icon',
  props: {
    name: {
      type: String
    }
  },
  render (h) {
    const fullName = /\.svg$/.test(this.name) ? this.name : (this.name + '.svg')
    const icon = require('src/images/icons/' + fullName)
    let result = /([\w-_]+)\.(\w+)$/.exec(fullName)
    const [, name, type] = result
    if (type === 'svg') {
      return renderSVG(h, parser.parseFromString(icon, 'image/svg+xml'), {name})
    } else {
      return h('img', {
        attrs: {
          src: icon,
          name
        }
      })
    }
  }
}
